Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 自定义导航栏的高度
    statusBarHeight: getApp().globalData.statusBarHeight,
    navBarHeight: getApp().globalData.navBarHeight,
    // 位置信息
    latitude: getApp().globalData.latitude,
    longitude: getApp().globalData.longitude,
    //导航栏菜单列表
    windowWidth: getApp().globalData.winWidth,
    tabScroll: 0, //使得导航位置居中
    currentTab: 0,  //当前的分类tab
    currentTypeid: 0, //当前的分类的id
    //导航栏菜单列表
    baseImgUrl: getApp().globalData.IMG_URL,
    // 商圈数据
    pointId: '',
    pointName: '',
    pointInfo: {} as any,
    // 
    scenicImgs: [] as string[],
    maxPageSize: 10,
    serveTypes: [] as any,
    servePath: '',
    serveName: '推荐',
    vipHotGoodsList: [],
    foodStoreList: [],
    parkingList: [],
    happyStoreList: [],
    shoppingStoreList: [],
    beautyworldStoreList: [],
    // 业务部分
    userInfo: {} as any,
    // 网络
    net_msg: "",
    ui_stroeJoin: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(option) {
    this.setData({ ui_stroeJoin: "商家入驻" });

    if (option.pointid != null) {// 其他页跳转时
      const pointId = option.pointid.toString();
      const pointName = option.name == null ? "黔乐多" : option.name;
      this.setData({ pointId: pointId, pointName: pointName });

      // 暂存数据
      wx.setStorageSync('defaultPointId', pointId);
      wx.setStorageSync('defaultPointName', pointName);

      // 加载商圈
      this.getTradeAreaByID(this.data.pointId)

      // 定位并加载
      this.getLocationAndLoadData(true);
    } else {
      console.error("参数：手动或第一次进入时")
      // 手动或第一次进入时
      // 查询商圈基础信息 1.获取缓存数据，不存在就先加载网络数据，有就先显示再加载
      var defaultPointId = null
      var defaultPointName = null
      try {
        // 看一下有没有上次打开的商圈
        defaultPointId = wx.getStorageSync('defaultPointId');
        defaultPointName = wx.getStorageSync('defaultPointName');
      } catch (error) {
      }

      if (defaultPointId != null && defaultPointId.length > 0) {// 判断是否需要记载网络数据
        console.error("参数：判断后走缓存")
        const pointid = defaultPointId.toString();
        const name = defaultPointName == null ? "黔乐多" : defaultPointName;
        this.setData({ pointId: pointid, pointName: name });

        // 商圈信息
        try {// 有商圈信息缓存时，先显示
          const pointInfo = wx.getStorageSync('pointInfo');
          this.setData({ pointInfo: pointInfo })
          // 推荐数据
          const vipHotGoodsList = wx.getStorageSync('vipHotGoodsList');
          if (vipHotGoodsList != null) {
            this.setData({ vipHotGoodsList: vipHotGoodsList, servePath: 'getVipNearbyHotGoodsPageByPointId' })
          }
          // console.error("vipHotGoodsList = "+JSON.stringify(vipHotGoodsList))
        } catch (error) {
        }
        // 加载商圈
        this.getTradeAreaByID(this.data.pointId)

        // 定位并加载
        this.getLocationAndLoadData(true);
      } else {
        console.error("无缓存数据定位后加载")
        // 参数：定位后再确定第一个商圈
        this.getLocationAndLoadData(false);
      }
    }

    //获取当前人信息
    try {
      const user = wx.getStorageSync('userInfo');
      this.setData({ userInfo: JSON.parse(user) });
    } catch (error) {
    }

    this.initNetworkStatusChange()
  },
  /**
   * 定位
   */
  getLocationAndLoadData(onlyLocate: boolean) {
    var that = this
    console.error("getLocation-start: 开始")
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      success(res) {
        // console.error("getLocation-success:" + JSON.stringify(res))
        const lat = res.latitude
        const lng = res.longitude

        // 当前页位置信息
        that.setData({ latitude: lat, longitude: lng })
        // 全局位置信息
        getApp().globalData.latitude = lat
        getApp().globalData.longitude = lng

        if (!onlyLocate) {// 没有现成数据，则需要先请求获得默认
          that.getNetNearbyPointList() //2024年8月6日 00:42:59
        } else {
          // 加载页面数据
          that.onPullDownRefresh()
          that.getNetNearbyPointList()
        }
      },
      fail(res) {
        console.error("getLocation-fail:" + JSON.stringify(res))
      }
    })
  },
  /**
   * 查询商圈并获取第一个商圈数据
   */
  getNetNearbyPointList() {
    var that = this
    const url = getApp().globalData.SERVER_URL + "fc/tradeArea/open/listForNearby"

    console.error("商圈列表this.data.latitude: " + this.data.latitude)
    console.error("商圈列表this.data.longitude: " + this.data.longitude)
    wx.request({
      url: url,
      method: 'GET',
      data: {
        pageNo: 1,
        pageSize: 1,
        // type: '1',
        latForLoc: this.data.latitude,
        lngForLoc: this.data.longitude
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
      },
      success(res: any) {
        // console.error("商圈列表结果: " + JSON.stringify(res))
        if (res.data.code == 200) {
          const list = res.data.result.records;
          if (list != null && list.length > 0) {
            const pointInfo = list[0]

            // console.error("data: " + JSON.stringify(that.data))
            if (that.data.pointId == null || that.data.pointId.length == 0) {
              // 没有默认值
              // console.error("商圈pointInfo: " + JSON.stringify(pointInfo))
              // 设置本页数据
              that.setData({ pointInfo: pointInfo, pointId: pointInfo.id, pointName: pointInfo.name })
              // 加载其他数据
              that.getTradeAreaByID(that.data.pointId)// 商圈数据
              that.onPullDownRefresh()// 推荐数据

              // 存储商圈数据
              wx.setStorageSync('defaultPointId', pointInfo.id);
              wx.setStorageSync('defaultPointName', pointInfo.name);
              wx.setStorageSync('pointInfo', pointInfo)

              wx.showToast({
                title: '欢迎来到 ' + pointInfo.name + ' !',
                icon: 'none',
                duration: 2000
              })

            } else if (that.data.pointId != null && that.data.pointId != pointInfo.id) {
              wx.showModal({
                title: '切换商圈',
                content: '您当前距离[ ' + pointInfo.name + " ]比较近，是否切换！",
                confirmText: '立即切换',
                cancelText: '知道了',
                success(res) {
                  if (res.confirm) {
                    // console.error("商圈pointInfo: " + JSON.stringify(pointInfo))
                    // 设置本页数据
                    that.setData({ pointInfo: pointInfo, pointId: pointInfo.id, pointName: pointInfo.name })
                    // 加载其他数据
                    that.getTradeAreaByID(that.data.pointId)// 商圈数据
                    that.onPullDownRefresh()// 推荐数据

                    // 存储商圈数据
                    wx.setStorageSync('defaultPointId', pointInfo.id);
                    wx.setStorageSync('defaultPointName', pointInfo.name);
                    wx.setStorageSync('pointInfo', pointInfo)
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
            } else {
              // 相同的区域就不提示
            }
          } else {
            console.error(JSON.stringify(res))
          }
        } else {
          console.error(JSON.stringify(res))
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },
  initNetworkStatusChange() {
    // 网络监听
    const that = this
    const listener = function (res: any) {
      // console.error("网络-onst listener = function：" + JSON.stringify(res))
      if (res.isConnected) {
        that.setData({ net_msg: '' })
      } else {
        that.setData({ net_msg: '当前网络不可用' })
      }
    }
    wx.onNetworkStatusChange(listener)

    // 弱网
    wx.onNetworkWeakChange(function (res) {
      // console.log(res.weakNet)
      // console.log(res.networkType)
      if (!res.weakNet) {// 好网
        that.setData({ net_msg: '好网' })
      } else {
        that.setData({ net_msg: '网络信号差[' + res.networkType + ']' })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 取消监听
    wx.offNetworkStatusChange()
    wx.offNetworkWeakChange()
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // this.getTradeAreaByID(this.data.pointId)

    // 加载推荐
    this.setData({ serveName: '推荐' })
    this.getPointPageList(this.data.pointId, '1782706419141357569', 'getVipNearbyHotGoodsPageByPointId');
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  showMsg(msg: string) {
    wx.showToast({
      title: msg,
      icon: 'success',
      duration: 2000
    })
  },
  /**
   * 打开详情-商家
   */
  toStoreDetail(param: any) {
    const bean = param.currentTarget.dataset.bean
    let storeId = bean.id
    console.error("storeId: " + storeId)
    wx.navigateTo({
      url: '/pages/apps/store/storeHome/storeHome',
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据  
        res.eventChannel.emit('acceptDataFromOpenerPage', { storeId: storeId })
      }
    })
  },
  /**
   * 打开详情-停车场
   */
  toParkingDetail(param: any) {
    console.error("toParkingDetail")
    wx.navigateTo({
      url: '/pages/apps/parking/parking-detail/parking-detail',
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('beanData', { bean: param.currentTarget.dataset.bean })
      }
    })
  },
  /**
   * 打开导航-停车场
   */
  toParkingNavi(param: any) {
    const item = param.currentTarget.dataset.bean
    // console.error("toParkingNavi:" + JSON.stringify(item))
    wx.openLocation({
      latitude: item.locLat, // 纬度，范围为-90~90，负数表示南纬
      longitude: item.locLng, // 经度，范围为-180~180，负数表示西经
      scale: 13, // 缩放比例
      name: item.name,
      address: item.address,
      success: function (r) {
        console.log(r)
      }
    })
  },
  /**
   * 切换商圈
   */
  toPointList() {
    wx.navigateTo({ url: '/pages/apps/poi/point/point-list/point-list' })
  },
  /**
   * 
   * @param pointId 查询商圈
   */
  getTradeAreaByID(pointId: string) {
    var that = this
    const preUrl = getApp().globalData.SERVER_URL
    const url = preUrl + "fc/tradeArea/open/queryOpenInfoById"
    // console.error("url: " + url)
    wx.request({
      url: url,
      method: 'GET',
      data: {
        id: pointId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
      },
      success(res: any) {
        // console.error("结果: " + JSON.stringify(res))
        wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          that.setData({ pointInfo: res.data.result })
          // 显示轮播图部分
          var logoArr = that.data.pointInfo.logo.split(',') as string[]
          that.setData({ scenicImgs: logoArr })

          if (that.data.pointInfo.pointStoreClsList != null && that.data.pointInfo.pointStoreClsList.length > 0) {
            that.setData({ serveTypes: that.data.pointInfo.pointStoreClsList })
          }
          // console.error("结果解析: " + JSON.stringify(that.data.pointInfo))

          wx.setStorageSync('pointInfo', that.data.pointInfo);
        } else {
          console.error(JSON.stringify(res))
        }
      },
    })
  },
  /**
   * 打开导航-停车场
   */
  openMapNavi(param: any) {
    console.error("toParkingNavi:" + JSON.stringify(param))
    const title = param.currentTarget.dataset.title
    const lat = param.currentTarget.dataset.lat
    const lng = param.currentTarget.dataset.lng
    const address = param.currentTarget.dataset.address

    console.error("toParkingNavi: title=" + title + ", lat=" + lat + ",lng=" + lng + ", address=" + address)

    wx.openLocation({
      latitude: lat, // 纬度，范围为-90~90，负数表示南纬
      longitude: lng, // 经度，范围为-180~180，负数表示西经
      scale: 13, // 缩放比例
      name: title,
      address: address,
      success: function (r) {
        console.log(r)
      }
    })
  },
  /**
   * 商务合作-入驻
   */
  toStoreJoin() {
    wx.navigateTo({ url: '/pages/base/about/biz-center/biz-center' })
  },
  /**
   * 
   * @param param 切换服务
   */
  switchTab(param: any) {
    const item = param.currentTarget.dataset.item
    this.switchLoad(item.id);// 门店分类ID
  },

  switchLoad(storeClsId: string) {
    for (let index = 0; index < this.data.serveTypes.length; index++) {
      const item = this.data.serveTypes[index];
      if (storeClsId == item.id) {
        item.hasSelected = true
        this.setData({ servePath: item.path })
        this.setData({ serveName: item.name })
      } else {
        item.hasSelected = false
      }
    }
    this.setData({ serveTypes: this.data.serveTypes })

    // 加载分页
    this.getPointPageList(this.data.pointId, storeClsId, this.data.servePath)
  },

  // -------------------------------------------------------------------------
  /**
    * Tabs数据列表
    * @param pointId 
    */
  getPointPageList(pointId: string, storeClsId: string, path: string) {
    // console.error(pointId + "," + storeClsId + "," + path)
    if ('getParkingPageByTradeAreaId' == this.data.servePath) {
      // 停车场
      this.getParkingPageByTradeAreaId(pointId)
    } else {
      // 默认加载门店数据
      this.getPointHomeStorePageData(pointId, storeClsId, path);
    }
  },

  /**
   * 获取店铺数据
   * @param pointId 
   * @param storeClsId 
   */
  getPointHomeStorePageData(pointId: string, storeClsId: string, path: string) {
    // 选中的tabs
    this.setData({ servePath: path })

    // 加载数据
    var that = this
    const preUrl = getApp().globalData.SERVER_URL
    const url = preUrl + "sys/open/store/getPointHomeStorePageData"
    wx.request({
      url: url,
      method: 'GET',
      data: {
        pageNo: 1,
        pageSize: that.data.maxPageSize,
        pointId: pointId,
        storeClsId: storeClsId,
        lat: getApp().globalData.latitude,
        lng: getApp().globalData.longitude
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
      },
      success(res: any) {
        // console.error("getFoodStorePageByPointId: " + JSON.stringify(res))
        wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          const list = res.data.result.records;
          if (list != null && list.length > 0) {
            for (let index = 0; index < list.length; index++) {
              const item = list[index];
              if (item.storeLogo != null) {
                var logoArr = item.storeLogo.split(',') as string[]
                item.logo = logoArr[0]
              }
            }
          }

          if ('getVipNearbyHotGoodsPageByPointId' == path) {// 热门
            that.setData({ vipHotGoodsList: list })
            wx.setStorageSync('vipHotGoodsList', list);// 缓存

          } else if ('getFoodStorePageByPointId' == path) {// 美食
            that.setData({ foodStoreList: list })

          } else if ('getHappyStorePageByPointId' == path) { // 休闲娱乐
            that.setData({ happyStoreList: list })

          } else if ('getShoppingStorePageByPointId' == path) { // 购物
            that.setData({ shoppingStoreList: list })

          } else if ('getBeautyworldStorePageByPointId' == path) { // 美容美发
            that.setData({ beautyworldStoreList: list })

          } else {

          }
        } else {
          console.error(JSON.stringify(res))
        }
      },
    })
  },

  /**
  * 获取停车场
  * @param tradeAreaId
  */
  getParkingPageByTradeAreaId(tradeAreaId: string) {
    this.setData({ servePath: 'getParkingPageByTradeAreaId' })
    var that = this
    const preUrl = getApp().globalData.SERVER_URL
    const url = preUrl + "fc/parking/open/pageByTradeAreaId"
    // console.error("@url: " + url)
    wx.request({
      url: url,
      method: 'GET',
      data: {
        pageNo: 1,
        pageSize: that.data.maxPageSize,
        tradeArea: tradeAreaId,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
        // 'X-Access-Token': token
      },
      success(res: any) {
        // console.error("@结果: " + JSON.stringify(res))
        wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          const list = res.data.result.records;
          if (list != null && list.length > 0) {
            for (let index = 0; index < list.length; index++) {
              const item = list[index];
              if (item.logo != null) {
                var logoArr = item.logo.split(',') as string[]
                item.logo = logoArr[0]
              }
            }
          }
          that.setData({ parkingList: list })
          // console.error("@结果2: " + JSON.stringify(list))
        } else {
          console.error(JSON.stringify(res))
        }
      },
    })
  },
  //--------------------------------------- 单击导航栏
  clickMenu: function (e: any) {
    // tab处理
    var current = e.currentTarget.dataset.current //获取当前tab的index
    var tabWidth = this.data.windowWidth / 5 // 导航tab共5个，获取一个的宽度
    var typeid = e.currentTarget.dataset.typeid; //获取当前的类型id
    this.setData({
      tabScroll: (current - 2) * tabWidth, //使点击的tab始终在居中位置
      currentTypeid: typeid,
      currentTab: current
    })

    // 子页面处理
    const item = e.currentTarget.dataset.item
    this.setData({ servePath: item.path })
    this.setData({ serveName: item.name })

    // 加载分页
    this.getPointPageList(this.data.pointId, typeid, this.data.servePath)
  },
  //--------------------------------------- 单击导航栏

  // ------------------------ 打开更多服务 -------------
  toServeMorePage(param: any) {
    // console.error("param参数：" + JSON.stringify(param))
    const path = param.currentTarget.dataset.path
    const point = param.currentTarget.dataset.point
    // console.error("param参数：servePath = " + path)
    // console.error("param参数：pointInfo = " + point)
    wx.navigateTo({
      url: '/pages/apps/poi/point/point-serve/point-serve',
      events: {
      },
      success: function (res) {
        res.eventChannel.emit('pageData', { path: path, point: point })
      }
    })
  },
  goUserCenterPage(param: any): void {
    // let pagePath = param.currentTarget.dataset.path 
    wx.navigateTo({
      url: '/pages/mine/mine', ///pages/order/orderHistory/orderHistory
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据  
        res.eventChannel.emit('acceptDataFromOpenerPage', { id: "test" })
      }
    })
  },
})